package com.hd.trans.ui.service;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.hd.trans.callback.OnCompletionListener;
import com.hd.trans.common.interf.IVoicePlayer;
import com.hd.trans.framework.tools.AppEvents;
import com.hd.trans.framework.tools.HuDunEvent;
import com.hd.trans.network.PreferenceMgr;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

/**
 * 播放服务
 */
public class VoicePlayService implements IVoicePlayer{

    private MediaPlayer mediaPlayer;//播放器
    private int playVoiceTimes;
    private Handler mHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            playVoiceTimes --;//循环播放次数减一
            mediaPlayer.start();
        }
    };

    public void release() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release(); // 释放硬件播放资源
        }
    }

    /**
     * 增强版Binder，扩展出播放音乐🎵行为
     */

    private MediaPlayer.OnCompletionListener completionListener;
    private OnCompletionListener listener;

    public VoicePlayService() {
        mediaPlayer = new MediaPlayer();
        if(completionListener != null){
            mediaPlayer.setOnCompletionListener(completionListener);
        }else {
            mediaPlayer.setOnCompletionListener(mp -> {
                if(playVoiceTimes > 1 && !mp.isPlaying()) {
                    mHandler.removeMessages(0);
                    mHandler.sendEmptyMessageDelayed(0,1000);
                }else {

                    postHuDunEvent(AppEvents.PLAY_COMPLETE);
                    if(listener != null){
                        listener.onCompletion(mp);
                    }
                }
            });
        }


        // 除了播放完成监听以外不需要监听 资源准备完成吗？
           /* mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (mediaPlayer != null) mediaPlayer.start();
                }
            });*/

    }

    public VoicePlayService getService() {
        return VoicePlayService.this;
    }

    /**
     * 播放语音
     *
     * @param filePath 文件的路径
     */
    @Override
    public void startPlay(String filePath) {
        try {
            mHandler.removeMessages(0);

            playVoiceTimes = PreferenceMgr.getInstance().getTranslatePreference().getVoiceTimes();
            if(playVoiceTimes >3){
                playVoiceTimes = 1000;//循环
            }

            mediaPlayer.reset();
            mediaPlayer.setDataSource(filePath);
//                mediaPlayer.setDataSource(getApplicationContext(), Uri.fromFile(new File(filePath)));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止播放
     */
    @Override
    public void stopPlay() {
        playVoiceTimes = 0;
        mHandler.removeMessages(0);
        mediaPlayer.stop();
    }

    @Override
    public boolean isPlaying() {
        //mediaPlayer.isPlaying()抛出异常 MediaPlayer ： java.lang.IllegalStateException at android.media.MediaPlayer.isPlaying(Native Method)
        try {
            return  mediaPlayer.isPlaying() || mHandler.hasMessages(0);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 让Activity可以获取到服务使用到MediaPlayer
     *
     * @return
     */
    @Override
    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    @Override
    public void setOnCompletionListener(OnCompletionListener listener) {

        this.listener = listener;
    }

    @Override
    public void setOnCompletionListener(MediaPlayer.OnCompletionListener listener) {
        this.completionListener = listener;
        if (mediaPlayer != null && listener != null) {
            mediaPlayer.setOnCompletionListener(listener);
        }
    }


    /****************************************事件传递******************************************/

    protected void postHuDunEvent(HuDunEvent<?> event) {
        if (null != event) {
            EventBus.getDefault().post(event);
        }
    }

    protected void postHuDunEvent(int eventCode) {
        postHuDunEvent(new HuDunEvent<>(eventCode, VoicePlayService.class));
    }


    protected void postHuDunEvent(int eventCode, Object data) {
        postHuDunEvent(new HuDunEvent<>(eventCode, data, VoicePlayService.class));
    }


}
